package spring.cloud.tasks.executor.listener.analyse;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import spring.cloud.tasks.executor.listener.TreeCacheListener;
import spring.cloud.tasks.executor.node.TaskNodePaths;
import spring.cloud.tasks.executor.task.statistics.ProcessCountStatistics;
import spring.cloud.tasks.executor.utils.log.LogUtils;

@Slf4j
@Setter
@Getter
class AnalyseResetListener extends TreeCacheListener {

    private final AnalyseResetListenerHolder analyseResetListener;

    public AnalyseResetListener(AnalyseResetListenerHolder analyseResetListener) {
        this.analyseResetListener = analyseResetListener;
    }

    @Override
    protected void dataChanged(CuratorFramework curatorFramework, String path, TreeCacheEvent treeCacheEvent) {
        if (analyseResetListener.isShutdown) {
            return;
        }
        if (TaskNodePaths.getTaskNodePath(analyseResetListener.taskId, AnalyseNode.analyse_reset).equals(path) && (TreeCacheEvent.Type.NODE_ADDED == treeCacheEvent.getType() || TreeCacheEvent.Type.NODE_UPDATED == treeCacheEvent.getType())) {
            if (ResetCountType.RESET_TOTAL_COUNT_DELTA_AND_FAILURE_COUNT_DELTA.equals(new String(treeCacheEvent.getData().getData()))) {
                LogUtils.info(log, analyseResetListener.taskId, "job:{} reset anaylse count.", analyseResetListener.taskId);
                ProcessCountStatistics.resetTotalCountDeltaAndFailureCountDelta(analyseResetListener.taskId, analyseResetListener.executorId);
            } else if (ResetCountType.RESET_SUCCESS_FAILURE_COUNT.equals(new String(treeCacheEvent.getData().getData()))) {
                LogUtils.info(log, analyseResetListener.taskId, "job:{} reset success/failure count", analyseResetListener.taskId);
                ProcessCountStatistics.resetSuccessFailureCount(analyseResetListener.taskId, analyseResetListener.executorId);
            }
        }
    }
}
